package mysql.ddl;

import com.google.common.base.Joiner;
import mysql.ColumnDefinition;
import mysql.MySQL;
import mysql.Schema;
import mysql.commands.SqlCommand;
import mysql.types.Type;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by nuno-rafael-figueiredo on 01-07-2014.
 */
public class CreateTable extends SqlCommand{
    private final String name;
    private List<ColumnDefinition> columnDefinitions = new ArrayList<>();

    public CreateTable(Schema schema, String name, ColumnDefinition... columnDefinitions) {
        super(schema.getConnection(), SqlStrategy.DO_NOTHING);
        this.columnDefinitions.addAll(Arrays.asList(columnDefinitions));
        this.name = schema.qualify() + "." + MySQL.wrap(name);
    }

    public String getSql() {
        return Joiner.on("\n").join(
                getSignature() + " (",
                getMembers(),
                ");"
        );
    }

    private String getSignature() {
        return "CREATE TABLE " + name;
    }

    public String getMembers() {
        List<String> pk = new ArrayList<>();
        List<Object> list = new ArrayList<>();

        for (ColumnDefinition columnDefinition : columnDefinitions) {
            list.add(columnDefinition);

            if (columnDefinition.primary())
                pk.add(MySQL.wrap(columnDefinition.getName()));
        }

        list.add("PRIMARY KEY (" + Joiner.on(", ").join(pk) + ")");

        return Joiner.on(",\n").join(list);
    }

    public void add(ColumnDefinition... columnDefinitions) {
        this.columnDefinitions.addAll(Arrays.asList(columnDefinitions));
    }

    public void createColumn(String name, Type type) {
        add(new ColumnDefinition(name, type));
    }
}
